package com.yu1996.service;


import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yu1996.constant.RedisConstant;
import com.yu1996.dao.SetmealDao;
import com.yu1996.entity.PageResult;
import com.yu1996.pojo.Setmeal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.Map;



/**
 *  @Description: 套餐Service实现类
 *  @author: xing
 *  @Date: 2021/7/3 15:18
 */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {


    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private JedisPool jedisPool;  //redis

    /**
     * @Description 添加套餐
     * @Author xing
     * @Date 2021/7/2 22:08
     * @Param 套餐基本信息、检查组的id数组
     */
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            //绑定套餐和检查组的多对多关系
            setSetmealAndCheckGroup(setmeal.getId(), checkgroupIds);
        }
        //将图片名称保存到Redis
        savePic2Redis(setmeal.getImg());

    }

    /**
     * @Description 分页查询套餐
     * @Author xing
     * @Date 2021/7/3 15:08
     * @Param 当前页、每页显示条数、查询条件
     * @Return 封装的分页查询结果集
     */
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = setmealDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }


    /**
     * @Description 将图片名称保存到Redis
     * @Author xing
     * @Date 2021/7/3 14:28
     * @Param
     * @Return
     * @Exception
     */
    private void savePic2Redis(String img) {
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, img);
    }

    /**
     * @Description 设置套餐和体检组的关系
     * @Author xing
     * @Date 2021/7/2 22:26
     * @Param 套餐id、体检组的id数组
     */
    private void setSetmealAndCheckGroup(Integer id, Integer[] checkgroupIds) {
        Map<String, Integer> map = null;
        for (Integer checkgroupId : checkgroupIds) {
            map = new HashMap<>();
            map.put("setmeal_id", id);
            map.put("checkgroup_id", checkgroupId);
            setmealDao.setSetmealAndCheckGroup(map);
        }
    }
}
